package com.supor.aiot.home.ui.device.config;

import android.content.Intent;
import android.os.Handler;
import android.provider.Settings;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.common.entity.parameter.ShowDialogParameter;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.NFCHelper;
import com.supor.aiot.common.utils.NFCCheckUtils;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivityNfcDeviceGuideBinding;
import com.supor.aiot.home.ui.device.AddDeviceActivity;
import com.supor.aiot.home.utils.PopUtils;
import com.supor.nfc.lib.utils.NfcUtils;

/**
 * @author Xiaozhuang
 * @date 2021/11/12
 * @description NFC绑定界面
 *
 */
@Route(path = PathUrl.PATH_NFC_DEVICE_GUIDE)
public class NFCDeviceGuideActivity extends BaseConfigActivity<NFCDeviceGuideViewModel, ActivityNfcDeviceGuideBinding> {

    private AppBasicDialog settingDialog;
    private AppBasicDialog failureDialog;
    private RecordBean recordBean;
//    private ProductType.ProductModel productModel;
    private DeviceInfo device;
    private DeviceInfo vrDevice;
    private String productId = "";

    @Override
    protected int resourceId() {
        return R.layout.activity_nfc_device_guide;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NfcUtils.mNfcAdapter == null) {
            NfcUtils.init(this);
            NfcUtils.configNfc(this);
        }
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.configNfc(this);
            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent,
                    null, null);
        }
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.getAllProduct();
        NfcUtils.init(this);
        PopUtils.getInstance().initNFCPop(this);

        viewModel.getBindResult().observe(this, result -> {
            if (result instanceof Result.Success) {
                PopUtils.getInstance().touchSuccess(R.string.nfc_dialog_tip1, null);
                GlobalDataCache.getBindDevice();
                new Handler().postDelayed(this::jumpToNextActivity, 2700);
            } else if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast("绑定设备失败");
                showNFCFailureDialog();
            }
        });

        viewModel.getUpdateResult().observe(this, result -> {
            if (result) {
                GlobalDataCache.getBindDevice();
                vrDevice.mac = recordBean.getSn();
                vrDevice.did = recordBean.getSn();
            }  else {
                Logc.e("更新UID失败");
            }
            device = vrDevice;
            PopUtils.getInstance().touchSuccess(R.string.nfc_dialog_tip1, null);
            // 跳转小程序
            new Handler().postDelayed(this::jumpToNextActivity, 2700);
        });
    }

    public void initView() {
        super.initView();
        bindingView.setViewM(this);
        Intent intent = getIntent();
        if (intent != null) {
            productId = intent.getExtras().getString("productId");
        }
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());

        String tip = getString(R.string.bind_nfc_guide_step2);
        SpannableString ss2 = new SpannableString(tip);

        ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvTextStep1.setText(ss2);

        // 碰一碰动图切换
        if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_blender);
        } else if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_es_c18);
        } else if (Constants.Type.VOLTAGE_POT.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_vp);
        } else if (Constants.Type.VOLTAGE_POT_C100.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_vp_3l);
        } else if (Constants.Type.ELECTRIC_SAUCEPAN.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_es);
        } else if (Constants.Type.BLENDER_66R.equalsIgnoreCase(productId)) {
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_66r);
        } else if (Constants.Type.BLENDER_65S.equalsIgnoreCase(productId)) {
            // TODO: 2022/2/28   换图
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_66r);
        } else if (Constants.Type.BLENDER_906R.equalsIgnoreCase(productId)) {
            // TODO: 2022/2/28  换图
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_66r);
        } else if (Constants.Type.BLENDER_905S.equalsIgnoreCase(productId)) {
            // TODO: 2022/2/28  换图
            bindingView.gifImage.setImageResource(R.drawable.gif_nfc_66r);
        }

        processNFC();

        bindingView.btnNextStep.setOnClickListener(v -> {
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                return;
            }
            if (NfcUtils.NFC_STATE == 1) {
                showDialog("提示", "该机型不支持NFC功能");
                return;
            }
            PopUtils.getInstance().showNFCPop(NFCDeviceGuideActivity.this, bindingView.llRoot);
        });
        bindingView.btnCancel.setOnClickListener(v -> finish());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcUtils.mNfcAdapter == null) {
            NfcUtils.init(this);
            NfcUtils.configNfc(this);
        }
        if (!PopUtils.getInstance().isNFCPopShow()) {
            return;
        }

        recordBean = NFCHelper.getInstance().processIntent(intent);
        if (recordBean != null) {

            // WiFi类NFC模块存在没有pid的情况
            if (TextUtils.isEmpty(recordBean.getProductId())) {
                showDialog("提示","设备选择错误\n请选择正确的设备");
                return;
            }

            // Pid是否已接入Saas后台
            if (!NFCCheckUtils.checkPidAccess(recordBean.getProductId())) {
                PopUtils.getInstance().dismissNFCPop();
                new Handler().postDelayed(() -> {
                    NFCCheckUtils.startResultActivity(this, NFCCheckUtils.STATUS_NO_EXIT, false);
                }, 500);
            } else {
                // 优先判断碰一碰设备类型是否匹配
                if (!productId.equalsIgnoreCase(recordBean.getProductId())) {
//                    if (Constants.Type.TYPE_BLENDER_Q8.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "免手洗破壁机(Q8)"));
//                    } else if (Constants.Type.ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "电炖锅(DG35YC18)"));
//                    } else if (Constants.Type.VOLTAGE_POT.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "电压力锅(SY-50HC37Q)"));
//                    } else if (Constants.Type.VOLTAGE_POT_C100.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "电压力锅(SY-30YZ100)"));
//                    } else if (Constants.Type.ELECTRIC_SAUCEPAN.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "电蒸锅(ZN2030FC823)"));
//                    } else if (Constants.Type.BLENDER_66R.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "破壁机(SP66R)"));
//                    }  else if (Constants.Type.BLENDER_65S.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "破壁机(SP65S)"));
//                    }  else if (Constants.Type.BLENDER_906R.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "破壁机(SP906R)"));
//                    }  else if (Constants.Type.BLENDER_905S.equalsIgnoreCase(productId)) {
//                        showDialog("提示", String.format(getString(R.string.device_productId_check), "破壁机(SP905S)"));
//                    }
                    showDialog("提示", "设备选择错误\n请选择正确的设备");
                    return;
                }

                // 检查是否为标签
                if (Constants.Type.VOLTAGE_POT.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.VOLTAGE_POT_C100.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.ELECTRIC_SAUCEPAN.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.BLENDER_66R.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.BLENDER_65S.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.BLENDER_906R.equalsIgnoreCase(recordBean.getProductId())
                        || Constants.Type.BLENDER_905S.equalsIgnoreCase(recordBean.getProductId())) {
                    // 判断pid是否已经绑定
                    DeviceInfo deviceInfo = NFCCheckUtils.getDeviceInfoByPid(productId);
                    if (deviceInfo != null) {
                        // 如果绑定直接跳转
                        PopUtils.getInstance().dismissNFCPop();
                        new Handler().postDelayed(
                                () -> {
                                    if (Constants.Type.VOLTAGE_POT.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT, GsonUtil.getInstance().toJson(deviceInfo));
                                    } else if (Constants.Type.VOLTAGE_POT_C100.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L, GsonUtil.getInstance().toJson(deviceInfo));
                                    } else if (Constants.Type.ELECTRIC_SAUCEPAN.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN, GsonUtil.getInstance().toJson(deviceInfo));
                                    } else if (Constants.Type.BLENDER_66R.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R, GsonUtil.getInstance().toJson(deviceInfo));
                                    }  else if (Constants.Type.BLENDER_65S.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S, GsonUtil.getInstance().toJson(deviceInfo));
                                    }  else if (Constants.Type.BLENDER_906R.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R, GsonUtil.getInstance().toJson(deviceInfo));
                                    }  else if (Constants.Type.BLENDER_905S.equalsIgnoreCase(productId)) {
                                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S, GsonUtil.getInstance().toJson(deviceInfo));
                                    }
                                }
                                , 500);
                    } else {
                        device = new DeviceInfo();
                        device.mac = NFCCheckUtils.generateUid(recordBean.getProductId(), true);
                        device.pid = recordBean.getProductId();

                        for (ProductType productType : GlobalDataCache.productTypeList) {
                            for (ProductType.ProductModel child : productType.Children) {
                                if (recordBean.getProductId().equalsIgnoreCase(child.productId)) {
                                    device.crmModelName = child.crmModelName;
                                    device.type = child.modelTypeId;
                                    device.model = child.modelId;
                                    device.productUrl = child.modelPicture;
                                    device.productName = child.modelTypeName;
                                    device.offStatusText = child.remark;
                                    break;
                                }
                            }
                        }

                        viewModel.bindNFCDevice(device.mac, device.model);
                    }
                    return;
                }

                // 获取虚拟mac
                vrDevice = NFCCheckUtils.getVirtualDeviceByPid(recordBean.getProductId());
                if (vrDevice != null) {
                    // 更新mac
                    viewModel.updateMac(recordBean.getSn(), vrDevice.mac);
                    return;
                }

                // NFC模块绑定
                device = new DeviceInfo();
                device.mac = recordBean.getSn();
                device.pid = recordBean.getProductId();

                for (ProductType productType : GlobalDataCache.productTypeList) {
                    for (ProductType.ProductModel child : productType.Children) {
                        if (recordBean.getProductId().equalsIgnoreCase(child.productId)) {
                            device.crmModelName = child.crmModelName;
                            device.type = child.modelTypeId;
                            device.model = child.modelId;
                            device.productUrl = child.modelPicture;
                            device.productName = child.modelTypeName;
                            device.offStatusText = child.remark;
                            break;
                        }
                    }
                }

                viewModel.bindNFCDevice(recordBean.getSn(), device.model);

            }
        } else {
            Logc.e(TAG, "record read failed");
            // 增加合法性校验
            String pkg = NFCHelper.getInstance().checkPKG(intent);
            int status = NFCCheckUtils.STATUS_ILLEGAL;
            switch (pkg) {
                case "com.midea.ai.appliances":
                    status = NFCCheckUtils.STATUS_ILLEGAL_MEDIA;
                    break;
                case "com.haier.uhome.uplus":
                    status = NFCCheckUtils.STATUS_ILLEGAL_HAIER;
                    break;
                case "com.joyoung.joyoungsmart":
                    status = NFCCheckUtils.STATUS_ILLEGAL_JOYA;
                    break;
                case "com.xiaomi.smarthome":
                    status = NFCCheckUtils.STATUS_ILLEGAL_XIAOMI;
                    break;
                default: break;
            }
            checkNFC(status);
//            showNFCFailureDialog();
        }
    }

    private void checkNFC(int status) {
        PopUtils.getInstance().dismissNFCPop();
        new Handler().postDelayed(
                () -> NFCCheckUtils.startResultActivity(this, status, false), 500);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (NfcUtils.mNfcAdapter != null) {
            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    public void updateNFCStatus(int state) {
        super.updateNFCStatus(state);
        NfcUtils.init(this);
        NfcUtils.configNfc(this);
        processNFC();
    }

    private void jumpToNextActivity() {
        // 跳转小程序
        if (Constants.Type.BLENDER_Q8.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN_C18.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_ELECTRIC_SAUCEPAN_C18, GsonUtil.getInstance().toJson(device));
            }
        }
        if (Constants.Type.TYPE_VOLTAGE_POT.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_VOLTAGE_POT_C100.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_VOLTAGE_POT_3L, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_ELECTRIC_SAUCEPAN.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_ELECTRIC_SAUCEPAN, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_BLENDER_66R.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_66R, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_BLENDER_65S.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_65S, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_BLENDER_905S.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_905S, GsonUtil.getInstance().toJson(device));
            }
        } else if (Constants.Type.TYPE_BLENDER_906R.equalsIgnoreCase(device.model)) {
            if (AppAgent.h5Debug) {
                AppAgent.startDebugTiny(this, Constants.App.PAGE_DEVICE, GsonUtil.getInstance().toJson(device), "");
            } else {
                AppAgent.startDevicePage(Constants.App.TINY_DEVICE_BLENDER_906R, GsonUtil.getInstance().toJson(device));
            }
        }

        // 销毁当前页面
        new Handler().postDelayed(() -> {
            setResult(1);
            finish();
        }, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NfcUtils.mNfcAdapter = null;
        PopUtils.getInstance().dismissNFCPop();
    }

    protected void processNFC() {
        if (NfcUtils.NFC_STATE == 2) {
            showNFCDialog();
        } else {
            closeNFCDialog();
        }
    }

    private void showNFCDialog() {
        if (settingDialog != null) {
            if (settingDialog.isShowing()) {
                return;
            } else {
                settingDialog.show();
            }
            return;
        }
        ShowDialogParameter parameter = new ShowDialogParameter()
                .setTitle(getString(com.supor.aiot.common.R.string.nfc_close))
                .setMsg(getString(com.supor.aiot.common.R.string.nfc_setting_tip))
                .setStrYes(getString(com.supor.aiot.common.R.string.setting))
                .setStrNo(getString(com.supor.aiot.common.R.string.cancel));
        settingDialog = DialogUtils.opDialog(this, parameter,
                (dialog, which) -> startActivity(new Intent(Settings.ACTION_NFC_SETTINGS)),
                (dialog, which) -> {
                    dialog.cancel();
                    finish();
                });
        settingDialog.show();
    }

    private void closeNFCDialog() {
        if (settingDialog != null && settingDialog.isShowing()) {
            settingDialog.dismiss();
        }
    }

    private void showNFCFailureDialog() {
        showDialog(getString(com.supor.aiot.common.R.string.nfc_touch_failure), getString(com.supor.aiot.common.R.string.nfc_touch_failure_tip));
    }

    private void showDialog(String title, String message) {
        PopUtils.getInstance().dismissNFCPop();
        if (failureDialog != null) {
            if (failureDialog.isShowing()) {
                return;
            } else {
                failureDialog.show();
            }
            return;
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(com.supor.aiot.common.R.string.ack, (dialog, which) -> {
            dialog.cancel();
            new Handler().postDelayed(() -> {
                startActivity(new Intent(this, AddDeviceActivity.class));
                setResult(1);
                finish();
            }, 500);
        });
        failureDialog = builder.create();
        failureDialog.setCancelable(false);
        failureDialog.show();
    }
}
